package com.wn.network.utils

import com.blankj.utilcode.util.LogUtils
import com.tencent.mmkv.MMKV
import com.wn.common.constant.HTTP_COOKIES_INFO
import javax.inject.Inject
import javax.inject.Singleton

/**
 * @Author: wn
 * @Date: 2024/7/29 16:49
 * @Description: Cookies管理 单例
 */
@Singleton
class CookiesManager @Inject constructor() {
  private val kv: MMKV by lazy {
    MMKV.defaultMMKV()
  }

/*
    init {
    MMKV.initialize(context, PathUtils.getInternalAppFilesPath())
  }
  */

  /**
   * 保存Cookies
   * @param cookies
   */
  fun saveCookies(cookies: String) {
    kv.encode(HTTP_COOKIES_INFO, cookies)
  }

  /**
   * 获取Cookies
   * @return cookies
   */
  fun getCookies(): String? = kv.decodeString(HTTP_COOKIES_INFO, "")

  /**
   * 清除Cookies
   */
  fun clearCookies() {
    saveCookies("")
  }

  /**
   * 解析Cookies
   * @param cookies List<String>?
   * @return String
   */
  fun encodeCookie(cookies: List<String>?): String {
    val sb = StringBuilder()
    val set = HashSet<String>()
    /**
     * 将 List.map --> 字符串 以 ";"的正则拆分 得到 List,
     * dropLastWhile -->从后面开始根据条件去掉字符{ 如果是空的  },不满足条件则返回整个剩余字符串(剩余的有满足的不处理)
     * dropWhile --> 从前往后逐一去掉字符，直到不满足条件时则返回后面的字符串
     * List 转为  Array<String>
     * List<Array<String>> --> set
     * 遍历 set --> 去掉最后一个 ; --> String
     */
/*    cookies
      ?.map { cookie ->
        cookie.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
      }
      ?.forEach { array ->
        array.filterNot { set.contains(it) }.forEach { set.add(it) }
      }*/
    // 有数据后测试更改
    cookies?.apply {
      flatMap { cookie ->
        cookie.split(";".toRegex()).dropLastWhile { it.isEmpty() }
      }
      filterNot { set.contains(it) }
      forEach { set.add(it) }
    }
    LogUtils.e("cookiesList:$cookies")
    val ite = set.iterator()
    while (ite.hasNext()) {
      val cookie = ite.next()
      sb.append(cookie).append(";")
    }
    val last = sb.lastIndexOf(";")
    if (sb.length - 1 == last) {
      sb.deleteCharAt(last)
    }
    return sb.toString()
  }
}